module board_sim(
    input clk,           // 板载时钟
    input rst_button,    // 物理复位按钮
    input [3:0] n_switch, // 拨动开关设定n
    output [7:0] led_output // 显示结果的LED
);

wire rst; // 内部复位信号
assign rst = !rst_button; // 假设按钮按下时输出0，所以取反

// 斐波那契模块连接
wire [31:0] fib_result;
top fib_top(
    .clk(clk),
    .reset(rst),
    .n(n_switch),
    .result(fib_result)
);

// 将计算结果的低8位显示到LED上
assign led_output = fib_result[7:0];

endmodule

module top(
    input clk,
    input reset,
    input [3:0] n,
    output [31:0] result // 输出类型修改为32位，匹配fib模块
);
wire [31:0] temp;

fib myfib(
    .clk(clk),
    .rst(reset),
    .n(n),
    .result(temp)
);

assign result = temp;

endmodule

module fib(
    input clk,
    input rst,
    input [3:0] n,
    output [31:0] result
);

reg [31:0] ra, rb;
wire [31:0] wf;
reg [3:0] count;

ALU myalu(.a(ra), .b(rb), .op(4'b0001), .f(wf)); // 确保ALU实例化正确

always @(posedge clk)
begin
    if (rst)
    begin
        ra <= 0; // F(0) = 0
        rb <= 1; // F(1) = 1
        count <= 0;
    end
    else if (count < n)
    begin
        ra <= rb;
        rb <= wf;
        count <= count + 1'b1;
    end
end

assign result = ra; // 最终结果应该是ra
endmodule

module ALU(
    input [31:0] a,
    input [31:0] b,
    input [3:0] op,
    output reg [31:0] f,
    output reg c
);

always @(*)
begin
    case(op)
        4'b0000: begin f = 32'b0; c = 0; end
        4'b0001: begin {c, f} = a + b; end // 加法，处理进位
        4'b0010: begin f = a - b; c = 0; end // 减法，无进位
        4'b0011: begin f = a & b; c = 0; end // 逻辑AND
        4'b0100: begin f = a | b; c = 0; end // 逻辑OR
        4'b0101: begin f = a ^ b; c = 0; end // 逻辑XOR
        default: begin f = 32'b0; c = 0; end
    endcase
end
endmodule


module sim1;

reg clk = 0;
reg rst = 1'b1;
reg [3:0] n = 4'b1010;
wire [31:0] result;

top t(
    .clk(clk),
    .reset(rst),
    .n(n),
    .result(result)
);

// 生成时钟信号
always #10 clk = ~clk;

initial begin
    #11 rst = 1'b0;
    #200; // 运行一段时间以查看结果
    $finish;
end

initial begin
    $dumpfile("sim1.vcd");
    $dumpvars(0, sim1);
end

endmodule